package tech.aistar.day11;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 本类用来演示: 读写锁
 *
 * @author: success
 * @date: 2022/8/2 10:50 上午
 */
public class TableDemo {
    //缓存,读写操作的都是这个数据
    //private volatile Map<String,Object> maps = new HashMap<>();

    //定义一个读写锁
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    //获取读锁
    private Lock rLock = rwLock.readLock();

    //获取写锁
    private Lock wLock = rwLock.writeLock();

    public void write(){
        try {
            //写锁 - 互斥的,写写互斥
            wLock.lock();
            System.out.println(Thread.currentThread().getName()+":写线程enter!");
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+":写线程leave!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放读锁
            wLock.unlock();
        }
    }

    public void read(){
        //读锁 - 读读共享
        try {
            rLock.lock();
            System.out.println(Thread.currentThread().getName()+":读线程enter!");
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+":读线程leave!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放读锁
            rLock.unlock();
        }
    }
}
class tableDemoTest{
    public static void main(String[] args) {
        TableDemo t = new TableDemo();
        //创建5个读取的线程
        for (int i = 0; i < 5; i++) {
            //new Thread(()->t.read()).start();

            //写的线程
            new Thread(()->t.write()).start();
        }
    }
}